<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="评审编号" prop="assessCode">
        <el-input
          v-model="queryParams.assessCode"
          placeholder="请输入评审编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="vendorName">
        <el-input
          v-model="queryParams.vendorName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评审人姓名" prop="assessPerson">
        <el-input
          v-model="queryParams.assessPerson"
          placeholder="请输入评审人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评审日期" prop="assessDate">
        <el-date-picker clearable
                        v-model="queryParams.assessDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择评审日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.mes_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['md:vendorAssess:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['md:vendorAssess:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['md:vendorAssess:remove']"
              >删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['md:vendorAssess:export']"
              >导出</el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assessList">
      <el-table-column label="评审编号" align="center" prop="assessCode"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="vendorName"/>
      <el-table-column label="评审人" align="center" prop="assessPerson"/>
      <el-table-column label="评审人" align="center" prop="assessType"/>
      <el-table-column label="评审日期" align="center" prop="assessDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.assessDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="得分" align="center" prop="totalScore">
        <template slot-scope="scope">
          <span>{{ scope.row.totalScore }}/100</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              v-hasPermi="['md:vendorAssess:query']"
            >查看
            </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['md:vendorAssess:edit']"
            v-show="scope.row.status==='PREPARE' || scope.row.status==='DISALLOW'"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['md:vendorAssess:remove']"
            v-show="scope.row.status==='PREPARE' || scope.row.status==='DISALLOW'"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改供应商评审对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="评审编号" prop="assessCode">
              <el-input v-model="form.assessCode" placeholder="请输入评审编号" :readonly="optType!='add'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商">
                <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search"></el-button>
              </el-input>
              <VendorSelect ref="vendorSelect" @onSelected="onVendorSelected"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="vendorAddress">
              <el-input v-model="form.vendorAddress" readonly style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="vendorContact">
              <el-input v-model="form.vendorContact" readonly style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="vendorContactTel">
              <el-input v-model="form.vendorContactTel" readonly style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="评审人" prop="assessPerson">
              <el-input v-model="form.assessPerson" placeholder="请输入考察人姓名" readonly>
                <el-button slot="append" @click="handleSelectUser" icon="el-icon-search"></el-button>
              </el-input>
              <UserSelect ref="userSelect" @onSelected="onUserSelected"></UserSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评审日期" prop="assessDate">
              <el-date-picker clearable
                              v-model="form.assessDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择评审日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="评审类型" prop="assessType">
              <el-select v-model="form.assessType" placeholder="请选择评审类型" style="width: 100%">
                <el-option value="季度" label="季度"/>
                <el-option value="年度" label="年度"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="fileUrl">
              <FileUpload
                :limit="1"
                :fileSize="100"
                :fileType="fileType"
                :value="fileList"
                @onUploaded="handleUploaded"
                @onRemoved="handleRemoved">
              </FileUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row style="margin-bottom: 20px;">
          <el-col :span="1.5">
            <div style="font-size: 25px; margin-top: 3px">选择评审项目</div>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" style="margin-left: 20px;" @click="handleAddMdVendorAssessLine">
              选择
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="mdVendorAssessLineList" ref="mdVendorAssessLine" show-summary :summary-method="getSummaries">
          <el-table-column label="项目编号" prop="projectCode"/>
          <el-table-column label="项目描述" prop="projectDescription"/>
          <el-table-column label="评审类型" prop="assessType"/>
          <el-table-column label="分值" prop="projectScoreValue"/>
          <el-table-column label="得分" prop="score">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.score" :step="1" :min="0" :max="scope.row.projectScoreValue"
                               step-strictly></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDeleteMdVendorAssessLine(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button type="primary" @click="confirmForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择评审项目" :visible.sync="openSelected" width="80%" append-to-body>
      <el-table :data="mdVendorAssessProjectList" ref="projectTable" @selection-change="handleSelectionChange"
                height="550">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="项目编号" prop="projectCode" align="center"/>
        <el-table-column label="项目描述" prop="projectDescription" align="center"/>
        <el-table-column label="评审类型" prop="assessType" align="center"/>
        <el-table-column label="分值" prop="projectScoreValue" align="center"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSelectedProject">确 定</el-button>
        <el-button @click="cancelSelected">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看供应商评审详情" :visible.sync="viewOpen" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="评审编号" prop="assessCode">
              <el-input v-model="form.assessCode" placeholder="请输入评审编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="vendorAddress">
              <el-input v-model="form.vendorAddress" readonly style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="vendorContact">
              <el-input v-model="form.vendorContact" readonly style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="vendorContactTel">
              <el-input v-model="form.vendorContactTel" readonly style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="评审人" prop="assessPerson">
              <el-input v-model="form.assessPerson" placeholder="请输入考察人姓名" readonly>
              </el-input>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评审日期" prop="assessDate">
              <el-date-picker clearable
                              v-model="form.assessDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择评审日期"
                              readonly
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="评审类型" prop="assessType">
              <el-input v-model="form.assessType" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="fileUrl">
              <FileUpload
                :limit="1"
                :fileSize="100"
                :fileType="fileType"
                :optType="'view'"
                :value="fileList"
                @onUploaded="handleUploaded"
                @onRemoved="handleRemoved">
              </FileUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row style="margin-bottom: 20px;">
          <el-col :span="1.5">
            <div style="font-size: 25px; margin-top: 3px">评审项目</div>
          </el-col>
        </el-row>
        <el-table :data="mdVendorAssessLineList" ref="mdVendorAssessLine" show-summary :summary-method="getSummaries">
          <el-table-column label="项目编号" prop="projectCode"/>
          <el-table-column label="项目描述" prop="projectDescription"/>
          <el-table-column label="评审类型" prop="assessType"/>
          <el-table-column label="分值" prop="projectScoreValue"/>
          <el-table-column label="得分" prop="score"/>
          <el-table-column label="备注" prop="remark"/>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen===false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listAssess, getAssess, delAssess, addAssess, updateAssess} from "@/api/mes/md/vendorAssess";
import VendorSelect from "@/components/vendorSelect/single.vue";
import UserSelect from "@/components/userSelect/single.vue";
import {getUserProfile} from "@/api/system/user";
import {getToBeSelected} from "@/api/mes/md/vendorAssessProject";
import {genCode} from "@/api/system/autocode/rule"
export default {
  name: "Assess",
  components: {UserSelect, VendorSelect},
  dicts: ['mes_order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedMdVendorAssessLine: [],
      //评审项目选中集合
      selectedRows:[],
      // 非单个禁用
      //single: true,
      // 非多个禁用
      //multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商评审表格数据
      assessList: [],
      // 供应商评审明细表格数据
      mdVendorAssessLineList: [],
      //待选评审项目
      mdVendorAssessProjectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      optType:undefined,
      //选择评审项目弹出层
      openSelected: false,
      //查看弹出框
      viewOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assessCode: null,
        vendorName: null,
        assessPerson: null,
        assessDate: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        assessCode: [
          {required: true, message: "评审编号不能为空", trigger: "blur"}
        ],
        vendorName: [
          {required: true, message: "供应商不能为空", trigger: "blur"}
        ],
        assessPerson: [
          {required: true, message: "评审人姓名不能为空", trigger: "blur"}
        ],
        assessDate: [
          {required: true, message: "评审日期不能为空", trigger: "blur"}
        ],
        assessType:[
          {required: true, message: "评审类型不能为空", trigger: "blur"}
        ]
      },
      // 上传文件类型
      fileType: ["pdf", "jpg", "png", "jpeg", "rar", "zip"],
      // 上传文件列表
      fileList: [],
      user: {},
    };
  },
  created() {
    this.getList();
    this.getUser();
  },
  methods: {
    /** 查询供应商评审列表 */
    getList() {
      this.loading = true;
      listAssess(this.queryParams).then(response => {
        this.assessList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        assessCode: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorAddress: null,
        vendorContact: null,
        vendorContactTel: null,
        assessPersonId: null,
        assessPerson: null,
        assessDate: new Date().toISOString().split('T')[0],
        fileUrl: null,
        totalScore: null,
        status: 'PREPARE'
      };
      this.mdVendorAssessLineList = [];
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedRows= selection;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.handleAutoGenChange();
      this.form.assessPerson = this.user.nickName;
      this.form.assessPersonId = this.user.userId;
      this.open = true;
      this.optType='add';
      this.title = "添加供应商评审";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAssess(id).then(response => {
        this.form = response.data;
        response.data.fileUrl == null ? this.fileList = [] : this.fileList.push(response.data.fileUrl);
        this.mdVendorAssessLineList = response.data.mdVendorAssessLineList;
        this.open = true;
        this.optType='update';
        this.title = "修改供应商评审";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getAssess(id).then(response => {
        this.form = response.data;
        this.mdVendorAssessLineList = response.data.mdVendorAssessLineList;
        this.viewOpen = true;
      });
      this.optType='view';
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.mdVendorAssessLineList = this.mdVendorAssessLineList;
          let total = this.mdVendorAssessLineList.reduce((sum, e) => sum + e.projectScoreValue, 0)
          if (total != 100) {
            this.$modal.msgError("考察项目总分必须为100分");
            return;
          }
          if (this.form.id != null) {
            updateAssess(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAssess(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    confirmForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.mdVendorAssessLineList = this.mdVendorAssessLineList;
          let total = this.mdVendorAssessLineList.reduce((sum, e) => sum + e.projectScoreValue, 0)
          if (total != 100) {
            this.$modal.msgError("考察项目总分必须为100分");
            return;
          }
          this.form.status = 'CONFIRMED';
          if (this.form.id != null) {
            updateAssess(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAssess(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除供应商评审编号为"' + ids + '"的数据项？').then(function () {
        return delAssess(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 供应商评审项目选择按钮操作 */
    handleAddMdVendorAssessLine() {
    this.openSelected=true;
    this.checkedMdVendorAssessLine=this.mdVendorAssessLineList;
    this.getToBeSelectedProject();
    },
    /** 供应商评审明细删除按钮操作 */
    handleDeleteMdVendorAssessLine(row) {
      this.mdVendorAssessLineList.splice(this.mdVendorAssessLineList.indexOf(row), 1)
    },
    /** 导出按钮操作 */
    /*handleExport() {
      this.download('md/assess/export', {
        ...this.queryParams
      }, `assess_${new Date().getTime()}.xlsx`)
    }*/
    //供应商选择
    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
    },
    //供应商选择弹出框
    onVendorSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        this.form.vendorAddress = obj.address;
        if (obj.contact1 != null && obj.contact1Tel != null) {
          this.form.vendorContact = obj.contact1;
          this.form.vendorContactTel = obj.contact1Tel;
        } else {
          this.form.vendorContact = obj.contact2;
          this.form.vendorContactTel = obj.contact2Tel;
        }
      }
    },
    handleSelectUser() {
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.assessPerson = obj.nickName;
        this.form.assessPersonId = obj.id;
      }
    },
    // 获取登录用户
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    handleUploaded(data) {
      this.form.fileUrl = data;
    },
    handleRemoved(data) {
      this.form.fileUrl = data;
    },
    //表尾合计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = []; //声明变量
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = " ";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (column.property === "projectScoreValue") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = "总分： " + sums[index];
        } else if (column.property === "score") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          this.form.totalScore = sums[index];
          sums[index] = "得分： " + sums[index];
        } else {
          sums[index] = '';
        }

      });
      return sums;
    },
    cancelSelected() {
      this.openSelected = false;
    },
    getToBeSelectedProject() {
      getToBeSelected().then(response=>{
        this.mdVendorAssessProjectList=response.data;
        this.$nextTick(function () {
          if (this.checkedMdVendorAssessLine.length > 0) {
            this.checkedMdVendorAssessLine.forEach(row => {
              let data = this.mdVendorAssessProjectList.find(item => item.projectId === row.projectId);
              if (data) {
                this.$refs.projectTable.toggleRowSelection(data);
              }

            })
          }
        })
      })
    },
    saveSelectedProject() {
      if (this.mdVendorAssessLineList.length && this.mdVendorAssessLineList.length > 0) {
        this.mdVendorAssessLineList.forEach((item, index) => {
          this.selectedRows.find((item1) => {
            if (item.projectId == item1.projectId) {
              item1.score = item.score;
              item1.remark = item.remark;
            }
          })
        })
      }
      this.mdVendorAssessLineList = this.selectedRows;
      this.openSelected = false;
    },
    //自动生成编码
    handleAutoGenChange() {
      genCode('VENDOR_ASSESS_CODE').then(response => {
        this.form.assessCode = response;
      });
    },
  }


};
</script>
